package de.jppietsch.gui;

import javax.swing.*;
import javax.swing.event.CellEditorListener;
import javax.swing.table.TableCellEditor;
import java.awt.*;
import java.util.EventObject;

/**
 * Created by IntelliJ IDEA.
 * User: user
 * Date: Feb 14, 2008
 * Time: 11:19:13 PM
 * To change this template use File | Settings | File Templates.
 */
public class MultiEditor implements TableCellEditor {

    private final static int BOOLEAN = 0;
    private final static int STRING = 1;
    private final static int INTEGER = 2;

    TableCellEditor[] cellEditors;


    int flg;

    public MultiEditor() {
        cellEditors = new TableCellEditor[INTEGER + 1];


        JCheckBox checkBox = new JCheckBox();
        checkBox.setOpaque(true);
        checkBox.setHorizontalAlignment(JLabel.CENTER);
        cellEditors[BOOLEAN] = new DefaultCellEditor(checkBox);
        JTextField textField = new JTextField();
        textField.setEditable(true);
        cellEditors[STRING] = new DefaultCellEditor(textField);
        cellEditors[INTEGER] = new SpinnerEditor();
        flg = INTEGER; // nobody
    }

    public Component getTableCellEditorComponent(JTable table, Object value,
                                                 boolean isSelected, int row, int column) {
        if (value instanceof Boolean) { // Boolean
            flg = BOOLEAN;
            return cellEditors[BOOLEAN].getTableCellEditorComponent(table, value, isSelected, row, column);
        } else if (value instanceof String) { // String
            flg = STRING;
            return cellEditors[STRING].getTableCellEditorComponent(table, value, isSelected, row, column);
        } else if (value instanceof Integer) {
            flg = INTEGER;
            return cellEditors[INTEGER].getTableCellEditorComponent(table, value, isSelected, row, column);
        } else {
            System.out.println("value = " + value.getClass());
        }
        return null;
    }

    public Object getCellEditorValue() {
        switch (flg) {
            case INTEGER:
            case BOOLEAN:
            case STRING:
                return cellEditors[flg].getCellEditorValue();
            default:
                return null;
        }
    }

    public boolean stopCellEditing() {
        return cellEditors[flg].stopCellEditing();
    }

    public void cancelCellEditing() {
        cellEditors[flg].cancelCellEditing();
    }

    public boolean isCellEditable(EventObject anEvent) {
        return cellEditors[flg].isCellEditable(anEvent);
    }

    public boolean shouldSelectCell(EventObject anEvent) {
        return cellEditors[flg].shouldSelectCell(anEvent);
    }

    public void addCellEditorListener(CellEditorListener l) {
        cellEditors[flg].addCellEditorListener(l);
    }

    public void removeCellEditorListener(CellEditorListener l) {
        cellEditors[flg].removeCellEditorListener(l);
    }

}
